package com.freak.kotlinfitnessserver.activity.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.freak.kotlinfitnessserver.activity.fragment.viewmodel.DeviceInfoViewModel
import com.freak.kotlinfitnessserver.app.App
import com.freak.kotlinfitnessserver.constant.DeviceConstant
import com.freak.kotlinfitnessserver.databinding.FragmentDeviceInfoBinding
import com.freak.kotlinfitnessserver.room.DeviceInfoData
import com.freak.kotlinfitnessserver.util.LogUtil
import com.freak.kotlinfitnessserver.util.ToastUtil
import kotlinx.coroutines.launch

class DeviceInfoFragment : Fragment() {
    private lateinit var binding: FragmentDeviceInfoBinding

    private lateinit var deviceType: String

    private val deviceInfoViewModel: DeviceInfoViewModel by activityViewModels {
        DeviceInfoViewModel.DeviceInfoViewModelFactory((activity?.application as App).fitnessDeviceDatabase.deviceInfoDataDao())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentDeviceInfoBinding.inflate(inflater, container, false)
        initClickListener()
        initData()
        return binding.root
    }

    private fun initData() {
        arguments ?: let {
            LogUtil.e(TAG, "arguments is null")
            return
        }
        deviceType = requireArguments().getString(DeviceConstant.deviceType, "")
        binding.linearLayoutCompatUnlockCode.visibility =
            if (deviceType == DeviceConstant.treadmill) View.VISIBLE else View.GONE
        lifecycleScope.launch {
            val deviceInfoData = deviceInfoViewModel.getDeviceInfo(deviceType)
            deviceInfoData ?: let {
                LogUtil.e(TAG, "deviceInfoData is null")
                return@launch
            }
            LogUtil.i(TAG, "start update ui")
            binding.editTextUnlockCode.setText(deviceInfoData.unlockCode)
            binding.editTextSystemId.setText(deviceInfoData.systemId)
            binding.editTextModelNumber.setText(deviceInfoData.modelNumber)
            binding.editTextSerialNumber.setText(deviceInfoData.serialNumber)
            binding.editTextFirmwareRevision.setText(deviceInfoData.firmwareRevision)
            binding.editTextHardwareRevision.setText(deviceInfoData.hardwareRevision)
            binding.editTextManufacturerName.setText(deviceInfoData.manufacturerName)
            binding.editTextSoftwareRevision.setText(deviceInfoData.softwareRevision)
        }
    }

    private fun initClickListener() {
        binding.buttonSaveDeviceInfo.setOnClickListener {
            if (deviceType == DeviceConstant.treadmill && TextUtils.isEmpty(getUnlockCode())) {
                ToastUtil.toastShort("请输入6位解锁码")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getSystemId())) {
                ToastUtil.toastShort("请输入SystemID")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getModelNumber())) {
                ToastUtil.toastShort("请输入ModelNumber")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getSerialNumber())) {
                ToastUtil.toastShort("请输入SerialNumber")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getFirmwareRevision())) {
                ToastUtil.toastShort("请输入FirmwareRevision")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getHardwareRevision())) {
                ToastUtil.toastShort("请输入HardwareRevision")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getSoftwareRevision())) {
                ToastUtil.toastShort("请输入SoftwareRevision")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getManufacturerName())) {
                ToastUtil.toastShort("请输入ManufacturerName")
                return@setOnClickListener
            }
            lifecycleScope.launch {
                val deviceInfoData = deviceInfoViewModel.getDeviceInfo(deviceType)
                LogUtil.i(TAG, "deviceInfoData = ${deviceInfoData.toString()}")
                deviceInfoData ?: let {
                    // 插入数据到数据库
                    val insertDeviceInfoData = DeviceInfoData(
                        deviceType = deviceType,
                        unlockCode = getUnlockCode(),
                        systemId = getSystemId(),
                        modelNumber = getModelNumber(),
                        serialNumber = getSerialNumber(),
                        firmwareRevision = getFirmwareRevision(),
                        hardwareRevision = getHardwareRevision(),
                        softwareRevision = getSoftwareRevision(),
                        manufacturerName = getManufacturerName()
                    )
                    deviceInfoViewModel.insertDeviceInfo(insertDeviceInfoData)
                    return@launch
                }
                // 已存在，更新
                val updateDeviceInfoData = DeviceInfoData(
                    id = deviceInfoData.id,
                    deviceType = deviceInfoData.deviceType,
                    unlockCode = getUnlockCode(),
                    systemId = getSystemId(),
                    modelNumber = getModelNumber(),
                    serialNumber = getSerialNumber(),
                    firmwareRevision = getFirmwareRevision(),
                    hardwareRevision = getHardwareRevision(),
                    softwareRevision = getSoftwareRevision(),
                    manufacturerName = getManufacturerName()
                )
                deviceInfoViewModel.updateDeviceInfo(updateDeviceInfoData)
            }
        }
    }

    private fun getUnlockCode(): String {
        return binding.editTextUnlockCode.text.trim().toString()
    }

    private fun getSystemId(): String {
        return binding.editTextSystemId.text.trim().toString()
    }

    private fun getModelNumber(): String {
        return binding.editTextModelNumber.text.trim().toString()
    }

    private fun getSerialNumber(): String {
        return binding.editTextSerialNumber.text.trim().toString()
    }

    private fun getFirmwareRevision(): String {
        return binding.editTextFirmwareRevision.text.trim().toString()
    }

    private fun getHardwareRevision(): String {
        return binding.editTextHardwareRevision.text.trim().toString()
    }

    private fun getSoftwareRevision(): String {
        return binding.editTextSoftwareRevision.text.trim().toString()
    }

    private fun getManufacturerName(): String {
        return binding.editTextManufacturerName.text.trim().toString()
    }

    companion object {
        const val TAG: String = "DeviceInfoFragment"

        @JvmStatic
        fun newInstance(deviceType: String) = DeviceInfoFragment().apply {
            arguments = Bundle().apply {
                putString(DeviceConstant.deviceType, deviceType)
            }
        }
    }
}